#!/bin/bash 
#This is a ShellScript For Auto DB Backup 
#Powered by husl 
#2015-01
#2015/9/10  jk409 优化
#1.可以使用参数来选择备份，备份名称时间更具体;
#2.备份目录修改为/data/backup
#3.添加了备份时需要主机IP和密码
#-------Setting----------------#
hosts='127.0.0.1' 
DBName=msccms
DBUser=root 
DBPasswd='root' 
BackupPath=/data/backup/msccms
LogFile=/data/backup/db.log 
DBPath=/var/lib/mysql/ 
BackupMethod=$1
#BackupMethod=mysqldump 
#BackupMethod=mysqlhotcopy 
#BackupMethod=tar 
#------Setting End------------# 

NewFile="$BackupPath"_$(date +%y%m%d_%H%M%S).tgz 
DumpFile="$BackupPath"_$(date +%y%m%d_%H%M%S) 
OldFile="${BackupPath}_$(date +%y%m%d --date='5 days ago')_*.tgz" 

echo "-------------------------------------------" >> $LogFile 
echo $(date +"%y-%m-%d %H:%M:%S") >> $LogFile 
echo "--------------------------" >> $LogFile 
#Delete Old File
for i in `ls $OldFile`  
do 
if [ -f $i ];then 
   rm -f $i >> $LogFile 2>&1 
   echo "[$i]Delete Old File Success!" 
else 
   echo "[$i]No Old Backup File!"  
fi 
done  >> $LogFile 2>&1

if [ -f $NewFile ] 
then 
   echo "[$NewFile]The Backup File is exists,Can't Backup!" >> $LogFile 
else 
   case $BackupMethod in 
   mysqldump) 
      if [ -z $DBPasswd ] 
      then 
         mysqldump -u $DBUser --opt $DBName > $DumpFile  
      else 
         mysqldump -h $hosts -u $DBUser -p$DBPasswd --opt $DBName > $DumpFile 
      fi 
      tar czvf $NewFile $DumpFile >> $LogFile 2>&1 
      echo "[$NewFile]Backup Success!" >> $LogFile 
      rm -rf $DumpFile 
      ;; 
   mysqlhotcopy) 
      rm -rf $DumpFile 
      mkdir $DumpFile 
      if [ -z $DBPasswd ] 
      then 
         mysqlhotcopy -u $DBUser $DBName $DumpFile >> $LogFile 2>&1 
      else 
         mysqlhotcopy -u $DBUser -p $DBPasswd $DBName $DumpFile >>$LogFile 2>&1 
      fi 
      tar czvf $NewFile $DumpFile >> $LogFile 2>&1 
      echo "[$NewFile]Backup Success!" >> $LogFile 
      rm -rf $DumpFile 
      ;; 
   *) 
      /etc/init.d/mysqld stop >/dev/null 2>&1 
      tar czvf $NewFile $DBPath$DBName >> /dev/null 2>&1 
      /etc/init.d/mysqld start >/dev/null 2>&1 
      echo "[$NewFile]Backup Success!" >> $LogFile 
      ;; 
   esac 
fi 

echo "-------------------------------------------" >> $LogFile